﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Threading;
using System.Collections;

namespace INSAForManagers
{
    public partial class FormEducation : Form
    {
        private FormACard fParent;
        private DataTable tbl;
        private string fileName;

        public FormEducation(FormACard parent)
        {
            InitializeComponent();
            fParent = parent;
            tbl = new DataTable();
        }

        private void FormEducation_Load(object sender, EventArgs e)
        {
            try
            {
                addColumns();

                initGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인");
            }
        }

        private void addColumns()
        {
            DataColumn col = null;

            //구분
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "구분";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육기관
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "교육기관";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //연수과정명
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "연수과정명";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //이수번호
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "이수번호";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육기간_시작
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "교육기간(시작)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육기간_끝
            col = new DataColumn();
            col.DataType = Type.GetType("System.DateTime");
            col.ColumnName = "교육기간(끝)";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육시간
            col = new DataColumn();
            col.DataType = Type.GetType("System.Int32");
            col.ColumnName = "교육시간";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육성적
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "교육성적";
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //평정점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "평정점";
            col.AllowDBNull = false;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            dgvEducationList.DataSource = tbl;

            dgvEducationList.Columns[0].Width = 70;
            dgvEducationList.Columns[1].Width = 80;
            dgvEducationList.Columns[2].Width = 80;
            dgvEducationList.Columns[3].Width = 100;
            dgvEducationList.Columns[4].Width = 70;
            dgvEducationList.Columns[5].Width = 70;
            dgvEducationList.Columns[6].Width = 70;
            dgvEducationList.Columns[7].Width = 60;
            dgvEducationList.Columns[7].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvEducationList.Columns[8].Width = 60;
            dgvEducationList.Columns[8].DefaultCellStyle.Format = "#0.0000";
            dgvEducationList.Columns[8].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

        }


        private void initGrid()
        {
            string pcode = fParent.txtPCode.Text;
            if (pcode.Equals(""))
            {
                MessageBox.Show("대상자를 입력 후에 다시 시도하세요!   ", "확인");
                this.Close();
                return;
            }

            ArrayList list = DBUtil.getListFromEduTable(pcode);
            for (int i = 0; i < list.Count; i++)
            {
                ArrayList data = (ArrayList)list[i];

                DataRow row = tbl.NewRow();
                row[0] = data[2].ToString();
                row[1] = data[3].ToString();
                row[2] = data[4].ToString();
                row[3] = data[5].ToString();
                row[4] = DateTime.Parse(data[6].ToString());
                row[5] = DateTime.Parse(data[7].ToString());
                row[6] = Int32.Parse(data[8].ToString());
                row[7] = Double.Parse(data[9].ToString());
                row[8] = Double.Parse(data[10].ToString());

                tbl.Rows.Add(row);
            }

            dgvEducationList.DataSource = tbl;
        }

        private void clearDGV()
        {
            tbl.Rows.Clear();
            dgvEducationList.DataSource = tbl;
        }

        private void lnkXlsRead_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "엑셀 파일(*.xls) | *.xls";
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                fileName = dlg.FileName;
                Thread t = new Thread(new ThreadStart(readXlsList));
                t.Start();
            }

            lnkSave.Enabled = false;
        }

        /// <summary>
        /// 승진후보자명부 작서용 엑셀 양식을 읽어 들인다.
        /// 교육구분 : 자격연수(9점)/직무연수(18점)
        /// 교육기관 : 
        /// 교육명 : 
        /// 이수번호 :
        /// 교육기간_시작 : 0000-00-00(10년 이내)
        /// 교육기간_마침 : 0000-00-00
        /// 교육시간 : 60시간 이상
        /// 교육성적 : 환산성적
        /// </summary>
        private void readXlsList()
        {
            try
            {
                clearDGV();

                Util.openXls(fileName);
                Util.changeSheet(4);

                Excel.Range range;

                /*
                 * 교사는 자격연수, 직무연수 3개까지 읽고 
                 * 교감은 자격연수, 직무연수 1개까지만 읽는다.
                 */
                int endline = 8;
                if (fParent.txtJobLevel.Text.Equals("교감")) endline = 6;

                range = Util.OSheet.get_Range("A5", "H" + endline);

                object[,] val = (object[,])range.get_Value(Missing.Value);


                if (val[1, 1] == null && val[2, 1] == null && val[3, 1] == null)
                {
                    MessageBox.Show("[교육성적]시트에 입력된 데이터가 없습니다.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Util.closeXls();
                    return;
                }
                

                if (!val[1, 1].ToString().Equals("자격연수"))
                {
                    MessageBox.Show("[교육성적]시트에 입력 데이터 첫 행은 [자격연수]를 입력하십시오.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Util.closeXls();
                    return;
                }

                //직무연수 카운트용 변수
                //직무연수인 경우만 1씩 증가 시킴
                int cnt = 0;

                for (int i = 1; i <= val.GetUpperBound(0); i++)
                {
                    //교육구분 값이 null이면 엑셀 읽기 중단
                    if (val[i, 2] == null)
                    {
                        Util.closeXls();
                        return;
                    }

                    //교육기간, 교육명, 이수번호 값이 없으면 경고
                    if (val[i, 2] == null || val[i, 3] == null || val[i, 4] == null || val[i, 2].ToString().Equals("") || val[i, 3].ToString().Equals("") || val[i, 4].ToString().Equals(""))
                    {
                        MessageBox.Show(i.ToString() + " 번째 행의 일부 데이터가 누락되었습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Util.closeXls();
                        return;
                    }

                    DataRow row = tbl.NewRow();
                    row[0] = val[i, 1].ToString().Trim();
                    row[1] = val[i, 2].ToString().Trim();
                    row[2] = val[i, 3].ToString();
                    row[3] = val[i, 4].ToString();
                    row[4] = DateTime.Parse(val[i, 5].ToString());
                    row[5] = DateTime.Parse(val[i, 6].ToString());
                    row[6] = val[i, 7].ToString();
                    if (val[i, 8] != null)
                    {
                        row[7] = val[i, 8].ToString();
                    }
                    else
                    {
                        row[7] = 0;
                    }                    

                    //교감이면 cnt = 0;
                    if (fParent.txtJobLevel.Text.Equals("교감")) cnt = 0;

                    double d = Util.getEduPointByTime(row[0].ToString(), fParent.txtJobLevel.Text, Double.Parse(row[7].ToString()), cnt);
                    row[8] = d;

                    tbl.Rows.Add(row);

                    //직무연수이면 cnt 값을 1증가
                    if (row[0].ToString().Equals("직무연수")) { cnt++; }

                }

                dgvEducationList.DataSource = tbl;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Util.closeXls();
            }
        }

        private void lnkSave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                DBUtil.beginTans();
                DBUtil.deleteFromEduTable(fParent.txtPCode.Text);

                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    ArrayList data = new ArrayList();
                    data.Add(fParent.txtPCode.Text);
                    data.Add((string)tbl.Rows[i][0]);
                    data.Add((string)tbl.Rows[i][1]);
                    data.Add(Util.removeSpecialChars((string)tbl.Rows[i][2]));
                    data.Add((string)tbl.Rows[i][3]);
                    data.Add(DateTime.Parse(tbl.Rows[i][4].ToString()));
                    data.Add(DateTime.Parse(tbl.Rows[i][5].ToString()));
                    data.Add((int)tbl.Rows[i][6]);
                    data.Add((double)tbl.Rows[i][7]);
                    data.Add((double)tbl.Rows[i][8]);
                    data.Add(DateTime.Now);

                    DBUtil.insertEduInfo(data);
                }
            }
            catch (Exception ex)
            {
                DBUtil.rollBack();
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DBUtil.commit();
            MessageBox.Show("저장하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnApply_Click(object sender, EventArgs e)
        {            

            string total_point = lblTotalPoint.Text;
            if (total_point.Equals("-"))
            {
                fParent.txtEduPoint.Text = "0.0";
            }
            else
            {
                fParent.txtEduPoint.Text = total_point;
            }
            this.Close();
        }

        private void lnkCalcEvalue_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            double total_point = 0.0;

            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                total_point += (double)tbl.Rows[i][8];
            }
            lblTotalPoint.Text = total_point.ToString("##.0000");

            lnkSave.Enabled = true;
        }
    }
}
